const express = require('express')
const returnUtil = require('../util/return')
const router = express.Router()
const userModel = require('../model/User')
const errorConst = require('../const/error')

let routerHelper = (function () {
  return {
    indexHandler: function (req, res, next) {
      console.log('getSession', req.session.loginUser, req.cookies)
      return returnUtil.success(res, req.session.loginUser)
    },
    loginHandler: async function (req, res, next) {
      if (!req.body.username || !req.body.password) {
        return returnUtil.error(res, errorConst.userLoginInfoEmpty)
      }
      let username = req.body.username
      let password = req.body.password
      let flag = await userModel.checkUser(username, password)
      if (!flag) {
        return returnUtil.error(res, errorConst.userLoginUsernameOrPasswordError)
      }
      req.session.loginUser = flag
      return returnUtil.success(res, flag)
    },
    checkLoginHandler: function (req, res, next) {
      if (req.session.loginUser) {
        return returnUtil.success(res, req.session.loginUser)
      }

      return returnUtil.error(res)
    },
    checkUserIsExistHandler: async function (req, res, next) {
      let username = req.body.username

      let flag = await userModel.checkUserIsExist(username)
      if (flag) {
        return returnUtil.error(res)
      }
      return returnUtil.success(res)
    },
    addUserHandler: function (req, res, next) {
      let username = req.body.username
      let nickname = req.body.nickname
      let password = req.body.password
      let data = {name: username, nickname: nickname, password: password}
      let flag = userModel.createByData(data)
      if (flag) {
        return returnUtil.success(res)
      }
      return returnUtil.error(res)
    }
  }
})()

router.get('/', routerHelper.indexHandler)
router.get('/check-login', routerHelper.checkLoginHandler)
router.post('/login', routerHelper.loginHandler)
router.post('/check-user-is-exist', routerHelper.checkUserIsExistHandler)
router.post('/add-user', routerHelper.addUserHandler)

module.exports = router
